<template>
    <div>
        <!-- 面包屑导航条 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <!-- 添加角色按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="roleslist" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['border-bottom', idex1===0?'border-top':'','vcenter']"
                            v-for="(item1,idex1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span='5'>
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级三级权限 -->
                            <el-col :span='19'>
                                <el-row :class="[index2===0?'':'border-top','vcenter']"
                                    v-for="(item2,index2) in item1.children" :key="item2.id">
                                    <!-- 二级权限渲染 -->
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 三级权限渲染 -->
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3,index3) in item2.children" :key="item3.id"
                                            closable @close="removeRightById(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditRole(scope.row)">编辑
                        </el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除
                        </el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting"
                            @click="showSetRightsDialog(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="50%" @close="setRightsDialogClosed">
            <el-tree :data="rightslist" :props="rightsTreeProps" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="defKeys" ref="rightsTreeRef">
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="addRoleDialogClosed">
            <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAddRole">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改角色对话框 -->
        <el-dialog title="修改角色" :visible.sync="editRoleDialogVisible" width="50%">
            <el-form :model="editRoleForm" :rules="editRoleRules" ref="editRoleRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEditRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                // 所有角色数据
                roleslist: [],
                setRightsDialogVisible: false,
                // 所有权限的数据
                rightslist: [],
                rightsTreeProps: {
                    children: 'children',
                    label: 'authName'
                },
                //默认选中的节点id值数组
                defKeys: [],
                roleId: '',
                addRoleDialogVisible: false,
                editRoleForm: {
                    roleName: '',
                    roleDesc: '',
                    id: ''
                },
                editRoleDialogVisible: false,
                editRoleRules: {
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ],
                    roleDesc: [
                        { required: false, message: '请输入角色描述', trigger: 'blur' }
                    ]
                },
                addRoleForm: {
                    roleName: '',
                    roleDesc: ''
                },
                addRoleRules: {
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' }
                    ],
                    roleDesc: [
                        { required: false, message: '请输入角色描述', trigger: 'blur' }
                    ]
                }
            }
        },
        created() {
            this.getRolesList()
        },
        methods: {
            async getRolesList() {
                const { data: res } = await this.$http.get('roles')
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.roleslist = res.data
            },
            async removeRightById(role, rightsId) {
                const ret = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => error)
                if (ret !== 'confirm') {
                    return this.$message.info('已取消删除该权限')
                }
                //确定删除事件
                const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
                console.log(res);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                //this.getRolesList()这样会导致权限栏关闭
                role.children = res.data
            },
            async showSetRightsDialog(role) {
                this.roleId = role.id
                // 获取所有权限数据
                const { data: res } = await this.$http.get('rights/tree')
                console.log(res);
                if (res.meta.status !== 200) return this.$message.error(res.mets.msg)
                // 把获取到的权限信息保存到data中
                this.rightslist = res.data
                // 递归获取三级节点id
                this.getLeafKeys(role, this.defKeys)
                this.setRightsDialogVisible = true

            },
            // 通过递归的形式，获取角色下所有的三级权限id，并保存到defKeys数组中
            getLeafKeys(node, arr) {
                if (!node.children) {
                    return arr.push(node.id)
                }
                node.children.forEach(element => {
                    this.getLeafKeys(element, arr)
                });
            },
            setRightsDialogClosed() {
                this.defKeys = []
            },
            // 点击为角色分配权限
            async allotRights() {
                const keys = [...this.$refs.rightsTreeRef.getCheckedKeys(),
                ...this.$refs.rightsTreeRef.getHalfCheckedKeys()]
                const keyStr = keys.join(',')
                const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
                    rids: keyStr
                })

                if (res.meta.status !== 200) return this.$message.error('分配角色权限失败')
                this.$message.success('分配用户权限成功')
                this.getRolesList()
                this.setRightsDialogVisible = false
            },
            //添加角色方法
            showAddRoleDialog() {
                this.addRoleDialogVisible = true

            },
            saveAddRole() {
                this.$refs.addRoleRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.post('roles', this.addRoleForm)
                    if (res.meta.status !== 201) return this.$message.error('添加角色失败')
                    this.$message.success('添加角色成功')
                    this.getRolesList()
                    this.addRoleDialogVisible = false
                })
            },
            addRoleDialogClosed() {
                this.$refs.addRoleRef.resetFields()
            },
            showEditRole(role) {
                this.editRoleForm.roleName = role.roleName
                this.editRoleForm.roleDesc = role.roleDesc
                this.editRoleForm.id = role.id
                this.editRoleDialogVisible = true
            },
            //保存编辑状态
            saveEditRole() {
                this.$refs.editRoleRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.put('roles/' + this.editRoleForm.id, {
                        roleName: this.editRoleForm.roleName,
                        roleDesc: this.editRoleForm.roleDesc
                    })
                    console.log(res);
                    if (res.meta.status !== 200) return this.$message.error('编辑角色失败')
                    this.$message.success('编辑角色成功')
                    this.getRolesList()
                    this.editRoleDialogVisible = false
                })
            },
            //删除角色
            async deleteRole(id) {
                const ret =await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error=>error)
                if(ret!=='confirm') return this.$message.info('已经取消删除操作')
                const { data: res } = await this.$http.delete('roles/' + id)
                if (res.meta.status !== 200) return this.$message.error('删除角色失败')
                this.$message.success('删除角色成功')
                this.getRolesList()
            }
        }

    }
</script>

<style lang="less" scoped>
    .el-tag {
        margin: 7px;
    }

    .border-top {
        border-top: 1px solid #eee;
    }

    .border-bottom {
        border-bottom: 1px solid #eee;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>